// 模拟数据
const analysisData = {
    // 关键指标
    keyMetrics: {
        totalThroughput: 12580,
        avgEfficiency: 45.6,
        equipmentUtilization: 82.3,
        avgWaitTime: 12.5
    },

    // 吞吐量趋势数据
    throughputTrend: {
        dates: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
        values: [1200, 1350, 1280, 1420, 1380, 1250, 1300]
    },

    // 设备效率数据
    equipmentEfficiency: {
        categories: ['岸桥', '龙门吊', 'AGV'],
        efficiency: [92, 88, 85],
        utilization: [85, 82, 78]
    },

    // 作业类型分布
    operationTypeDistribution: {
        types: ['装船', '卸船', '转运'],
        counts: [450, 380, 320],
        percentages: [39.1, 33.0, 27.9]
    },

    // 时间分布数据
    timeDistribution: {
        hours: Array.from({ length: 24 }, (_, i) => `${i}:00`),
        days: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
        data: Array.from({ length: 7 }, () =>
            Array.from({ length: 24 }, () => Math.floor(Math.random() * 100))
        )
    },

    // 详细数据表格
    detailedData: [{
            date: '2024-03-20',
            throughput: 12580,
            efficiency: 45.6,
            utilization: 82.3,
            waitTime: 12.5,
            distribution: '装船: 39.1%, 卸船: 33.0%, 转运: 27.9%'
        },
        {
            date: '2024-03-19',
            throughput: 11850,
            efficiency: 44.8,
            utilization: 81.5,
            waitTime: 13.2,
            distribution: '装船: 38.5%, 卸船: 34.2%, 转运: 27.3%'
        },
        {
            date: '2024-03-18',
            throughput: 12230,
            efficiency: 45.2,
            utilization: 81.8,
            waitTime: 12.8,
            distribution: '装船: 39.8%, 卸船: 32.5%, 转运: 27.7%'
        },
        {
            date: '2024-03-17',
            throughput: 11980,
            efficiency: 44.9,
            utilization: 81.2,
            waitTime: 13.5,
            distribution: '装船: 37.9%, 卸船: 33.8%, 转运: 28.3%'
        },
        {
            date: '2024-03-16',
            throughput: 12150,
            efficiency: 45.1,
            utilization: 81.6,
            waitTime: 13.0,
            distribution: '装船: 38.7%, 卸船: 33.5%, 转运: 27.8%'
        },
        {
            date: '2024-03-15',
            throughput: 12420,
            efficiency: 45.4,
            utilization: 82.0,
            waitTime: 12.7,
            distribution: '装船: 39.3%, 卸船: 32.8%, 转运: 27.9%'
        },
        {
            date: '2024-03-14',
            throughput: 12080,
            efficiency: 45.0,
            utilization: 81.4,
            waitTime: 13.3,
            distribution: '装船: 38.2%, 卸船: 33.6%, 转运: 28.2%'
        }
    ]
};

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', () => {
    // 初始化所有图表
    initCharts();
    // 更新关键指标
    updateKeyMetrics();
    // 更新详细数据表格
    updateDetailedTable();
    // 绑定事件监听器
    bindEventListeners();
});

// 初始化所有图表
function initCharts() {
    initThroughputTrend();
    initEquipmentEfficiency();
    initOperationTypeDistribution();
    initTimeDistribution();
}

// 初始化吞吐量趋势图
function initThroughputTrend() {
    const chart = echarts.init(document.getElementById('throughputTrend'));
    const option = {
        tooltip: {
            trigger: 'axis'
        },
        grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
        },
        xAxis: {
            type: 'category',
            data: analysisData.throughputTrend.dates,
            boundaryGap: false
        },
        yAxis: {
            type: 'value',
            name: 'TEU'
        },
        series: [{
            name: '吞吐量',
            type: 'line',
            smooth: true,
            data: analysisData.throughputTrend.values,
            areaStyle: {
                opacity: 0.1
            },
            lineStyle: {
                width: 3
            },
            itemStyle: {
                color: '#2196f3'
            }
        }]
    };
    chart.setOption(option);
}

// 初始化设备效率分析图
function initEquipmentEfficiency() {
    const chart = echarts.init(document.getElementById('equipmentEfficiency'));
    const option = {
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'shadow'
            }
        },
        legend: {
            data: ['效率', '利用率']
        },
        grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
        },
        xAxis: {
            type: 'category',
            data: analysisData.equipmentEfficiency.categories
        },
        yAxis: {
            type: 'value',
            name: '%'
        },
        series: [{
                name: '效率',
                type: 'bar',
                data: analysisData.equipmentEfficiency.efficiency,
                itemStyle: {
                    color: '#4caf50'
                }
            },
            {
                name: '利用率',
                type: 'bar',
                data: analysisData.equipmentEfficiency.utilization,
                itemStyle: {
                    color: '#ff9800'
                }
            }
        ]
    };
    chart.setOption(option);
}

// 初始化作业类型分布图
function initOperationTypeDistribution() {
    const chart = echarts.init(document.getElementById('operationTypeDistribution'));
    const option = {
        tooltip: {
            trigger: 'item',
            formatter: '{b}: {c} ({d}%)'
        },
        legend: {
            orient: 'vertical',
            left: 'left'
        },
        series: [{
            name: '作业类型分布',
            type: 'pie',
            radius: ['40%', '70%'],
            avoidLabelOverlap: false,
            itemStyle: {
                borderRadius: 10,
                borderColor: '#fff',
                borderWidth: 2
            },
            label: {
                show: false,
                position: 'center'
            },
            emphasis: {
                label: {
                    show: true,
                    fontSize: '20',
                    fontWeight: 'bold'
                }
            },
            labelLine: {
                show: false
            },
            data: analysisData.operationTypeDistribution.types.map((type, index) => ({
                name: type,
                value: analysisData.operationTypeDistribution.counts[index]
            }))
        }]
    };
    chart.setOption(option);
}

// 初始化热力图
function initHeatmap() {
    const chart = echarts.init(document.getElementById('timeDistribution'));
    const option = {
        tooltip: {
            position: 'top'
        },
        grid: {
            height: '80%',
            top: '10%'
        },
        xAxis: {
            type: 'category',
            data: analysisData.timeDistribution.hours,
            splitArea: { show: true }
        },
        yAxis: {
            type: 'category',
            data: analysisData.timeDistribution.days,
            splitArea: { show: true }
        },
        visualMap: {
            min: 0,
            max: 100,
            calculable: true,
            orient: 'horizontal',
            left: 'center',
            bottom: 0
        },
        series: [{
            name: '作业强度',
            type: 'heatmap',
            data: analysisData.timeDistribution.data.flatMap((dayData, dayIndex) =>
                dayData.map((value, hourIndex) => [hourIndex, dayIndex, value])
            ),
            label: { show: true },
            emphasis: {
                itemStyle: {
                    shadowBlur: 10,
                    shadowColor: 'rgba(0, 0, 0, 0.5)'
                }
            }
        }]
    };
    chart.setOption(option);
}

// 时间粒度切换事件
function setupTimeGranularity() {
    document.querySelectorAll('.chart-actions button').forEach(btn => {
        btn.addEventListener('click', function() {
            document.querySelectorAll('.chart-actions button').forEach(b => b.classList.remove('active'));
            this.classList.add('active');
            updateChartData(this.textContent);
        });
    });
}

// 动态加载详细数据
function loadDetailedData() {
    const tbody = document.getElementById('dataTableBody');
    tbody.innerHTML = analysisData.detailedData.map(item => `
        <tr>
            <td>${item.date}</td>
            <td>${item.throughput.toLocaleString()}</td>
            <td>${item.efficiency}</td>
            <td>${item.utilization}%</td>
            <td>${item.waitTime}</td>
            <td>${item.distribution}</td>
        </tr>
    `).join('');
}

// 窗口调整时重置图表尺寸
window.addEventListener('resize', () => {
    echarts.init(document.getElementById('throughputTrend')).resize();
    echarts.init(document.getElementById('equipmentEfficiency')).resize();
    echarts.init(document.getElementById('operationTypeDistribution')).resize();
    echarts.init(document.getElementById('timeDistribution')).resize();
});

// 更新关键指标
function updateKeyMetrics() {
    document.getElementById('totalThroughput').textContent = analysisData.keyMetrics.totalThroughput;
    document.getElementById('avgEfficiency').textContent = analysisData.keyMetrics.avgEfficiency;
    document.getElementById('equipmentUtilization').textContent = analysisData.keyMetrics.equipmentUtilization;
    document.getElementById('avgWaitTime').textContent = analysisData.keyMetrics.avgWaitTime;
}

// 更新详细数据表格
function updateDetailedTable() {
    const tbody = document.getElementById('dataTableBody');
    tbody.innerHTML = analysisData.detailedData.map(row => `
        <tr>
            <td>${row.date}</td>
            <td>${row.throughput}</td>
            <td>${row.efficiency}</td>
            <td>${row.utilization}</td>
            <td>${row.waitTime}</td>
            <td>${row.distribution}</td>
        </tr>
    `).join('');
}

// 绑定事件监听器
function bindEventListeners() {
    // 时间范围选择按钮
    document.querySelectorAll('.range-selector button').forEach(button => {
        button.addEventListener('click', () => {
            document.querySelectorAll('.range-selector button').forEach(btn => btn.classList.remove('active'));
            button.classList.add('active');
            // TODO: 根据选择的时间范围更新数据
        });
    });

    // 图表操作按钮
    document.querySelectorAll('.chart-actions button').forEach(button => {
        button.addEventListener('click', () => {
            const chartCard = button.closest('.chart-card');
            chartCard.querySelectorAll('.chart-actions button').forEach(btn => btn.classList.remove('active'));
            button.classList.add('active');
            // TODO: 根据选择的视图类型更新图表
        });
    });

    // 导出数据按钮
    document.querySelector('.btn-secondary').addEventListener('click', () => {
        // TODO: 实现数据导出功能
        alert('数据导出功能开发中...');
    });

    // 生成报告按钮
    document.querySelector('.btn-primary').addEventListener('click', () => {
        // TODO: 实现报告生成功能
        alert('报告生成功能开发中...');
    });
}